import { FunctionComponent } from 'react';
import { DndContext, useSensors, DragEndEvent, closestCenter, useSensor, MouseSensor } from '@dnd-kit/core';
import { sortableKeyboardCoordinates, SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
interface SortableContainerProps {
  children: React.ReactNode;
  items: Array<{ id: string; [key: string]: any }>;
  onDragEnd: (oldIndex: number, newIndex: number) => void;
}

const SortableContainer: FunctionComponent<SortableContainerProps> = (props: SortableContainerProps) => {
  const { children, items, onDragEnd } = props;
  const sensors = useSensors(
    useSensor(MouseSensor, {
      activationConstraint: {
        distance: 8, //8px 鼠标点击移动超过8像素才激活
      },
    }), //鼠标
  );
  const hanlderDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
    if (over == null) return;
    if (active.id !== over.id) {
      const oldIndex = items.findIndex((c) => c.id === active.id);
      const newIndex = items.findIndex((c) => c.id === over.id);
      onDragEnd(oldIndex, newIndex);
    }
  };
  return (
    <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={hanlderDragEnd}>
      <SortableContext items={items} strategy={verticalListSortingStrategy}>
        {children}
      </SortableContext>
    </DndContext>
  );
};

export default SortableContainer;
